package com.hyd.hx_adr.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.gson.io.GsonSerializer;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.UUID;


public class JWTUtils {

    /**
     * 默认有效期10个小时
     */
    private static final Long EXPIRE_TIME = 60*60*10000L;

    private static final String DEFAULT_KEY = "WFHJGOFIKHf9dsfkadshfkhgida44dg6agv658adbn8aes5f4gv61vc654dh6cbgnaZ6584cxzv6ertyuiopasdfghjklzxcvbnm12adg4a";

    /**
     * 生成随机字符串
     */
    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    /**
     * 生成jwt
     * @param value 建议存唯一字段 方便区分 一般存userId
     */
    public static String createJWT(String value){
        JwtBuilder jwtBuilder = getJwtBuilder(value, EXPIRE_TIME, getUUID());
        String compact = jwtBuilder.compact();
        return compact;
    }

    /**
     * 生成jwt 定时
     */
    public static String createJWT(String value, Long expireTime){
        JwtBuilder jwtBuilder = getJwtBuilder(value, expireTime, getUUID());
        String compact = jwtBuilder.compact();
        return compact;
    }


    /**
     * 获取jwt构造器
     */
    public static JwtBuilder getJwtBuilder(String value, Long expireTimes, String uuid){
        JwtBuilder builder = Jwts.builder();
        builder.setId(uuid);
        builder.compressWith(CompressionCodecs.DEFLATE);
        builder.setSubject(value);
        builder.setIssuer("xw");
//        builder.setIssuedAt(new Date(System.currentTimeMillis()));
//        builder.setExpiration(new Date(System.currentTimeMillis() + expireTimes));
        builder.signWith(generalKey(), SignatureAlgorithm.HS512);
        builder.serializeToJsonWith(new GsonSerializer<>());
        return builder;
    }

    /**
     * 生成加密密钥
     */
    public static SecretKey generalKey(){
        byte[] decode = Base64.getDecoder().decode(DEFAULT_KEY);
        SecretKey key = new SecretKeySpec(decode, "HmacSHA256");
        return key;
    }

    /**
     * 解析jwt
     */
    public static Claims parseJWT(String jwt){
        SecretKey key = generalKey();
        JwtParser build = Jwts.parserBuilder().setSigningKey(generalKey()).build();
        return build.parseClaimsJws(jwt).getBody();
    }
}
